<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
/**
 * Class EmergencyContact
 * Desc  紧急联系人控制器
 * Create on 2024/10/22 14:11
 * Create by wangyafang
 */

namespace app\api\controller\wddj\user;


use app\api\model\wddj\User;
use app\common\controller\Api;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class EmergencyContact extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['index','add','details','edit','del'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wddj\user\EmergencyContact();
    }
    
    /**
     * Desc 列表
     * Create on 2024/10/22 14:26
     * Create by wangyafang
     */
    public function index()
    {
        if (!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $wechat_id = User::getWechatId($this->auth->id);
        $where['wechat_id'] = array('eq',$wechat_id);

        $order = 'id desc';

        $data = $this->model
            ->where($where)
            ->field("id,mobile")
            ->order($order)
            ->select();

        foreach ($data as $v) {
            $v->mobile =   substr_replace($v['mobile'], '******', 3, -3);
        }

        $this->success('请求成功',$data);
    }
    
    /**
     * Desc 添加
     * Create on 2024/10/22 14:27
     * Create by wangyafang
     */
    public function add()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $wechat_id = User::getWechatId($this->auth->id);

        $param = $this->request->post();
        $create_data = array(
            'wechat_id'=>$wechat_id,
        );
        $create_data = array_merge($create_data,$param);
        $result = $this->validate($create_data,'app\api\validate\wddj\user\EmergencyContact');
        if(true !== $result){
            // 验证失败 输出错误信息
            $this->error($result);
        }

        $default_id =  $this->model->where([
            'wechat_id'=> $wechat_id,
            'set_priority'=>1,
        ])->value('id');
        if(isset($param['set_priority']) && $param['set_priority'] == 1 && $default_id) {
            $this->model->where('id',$default_id)->update([
                'set_priority'=>2,
            ]);
        }

        Db::startTrans();
        try {
            $this->model->data($create_data);
            $this->model->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('添加成功');

    }

    /**
     * Desc 详情
     * Create on 2024/11/26 15:54
     * Create by wangyafang
     */
    public function details()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $id = $this->request->get('id');
        $emergencyContactObj = $this->model->where('id',$id)->field('id,name,mobile,set_priority,wechat_id')->find();
        $wechat_id = User::getWechatId($this->auth->id);
        if ($emergencyContactObj['wechat_id'] != $wechat_id) {
            $this->error('不是本人，无法查看');
        }
        $emergencyContactObj->hidden(['wechat_id']);

        $this->success('请求成功',$emergencyContactObj);
    }

    /**
     * Desc 编辑
     * Create on 2024/10/22 14:27
     * Create by wangyafang
     */
    public function edit()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->post();
        $id = $param['id'];
        $emergencyContactObj = $this->model->get($id);
        if (!$emergencyContactObj) {
            $this->error('紧急联系人不存在');
        }
        if (empty($param['name'])) {
            $this->error('请输入姓名');
        }
        if (empty($param['mobile'])) {
            $this->error('请输入手机号码');
        }
        $wechat_id = User::getWechatId($this->auth->id);
        if ($emergencyContactObj['wechat_id'] != $wechat_id) {
            $this->error('不是本人，无法操作');
        }

        $emergencyContactObjQueryName = (new \app\api\model\wddj\user\EmergencyContact())
            ->where('id','<>',$param['id'])
            ->where('wechat_id',$wechat_id)
            ->where('name',$param['name'])
            ->find();
        if ($emergencyContactObjQueryName) {
            $this->error('姓名已存在');
        }

        if (!\think\Validate::regex($param['mobile'], "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        $emergencyContactObjQueryMobile = (new \app\api\model\wddj\user\EmergencyContact())
            ->where('id','<>',$param['id'])
            ->where('wechat_id',$wechat_id)
            ->where('mobile',$param['mobile'])
            ->find();
        if ($emergencyContactObjQueryMobile) {
            $this->error('手机号码已存在');
        }


        $default_id =  $this->model->where([
            'wechat_id'=> $wechat_id,
            'set_priority'=>1,
        ])->where('id','<>',$param['id'])->value('id');
        if(isset($param['set_priority']) && $param['set_priority'] == 1 && $default_id) {
            $this->model->where('id',$default_id)->update([
                'set_priority'=>2,
            ]);
        }

        Db::startTrans();
        try {
            $emergencyContactObj->save($param);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('编辑成功');

    }

    /**
     * Desc 删除
     * Create on 2024/10/22 10:35
     * Create by wangyafang
     */
    public function del()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $id = $this->request->post('id');
        $emergencyContactObj = $this->model->get($id);
        if (!$emergencyContactObj) {
            $this->error('紧急联系人不存在');
        }

        $wechat_id = User::getWechatId($this->auth->id);
        if ($emergencyContactObj['wechat_id'] != $wechat_id) {
            $this->error('不是本人，无法操作');
        }

        $result = false;
        Db::startTrans();
        try {
            $result = $emergencyContactObj->delete();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($result == false) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }
}



 